package com.chenjun.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

public class StreamUtils
{
	public static String converStreamToString(InputStream inputStream)
	{
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
		StringBuilder sb = new StringBuilder("");
		String line = "";
		try
		{
			while ((line = bufferedReader.readLine()) != null) // 按行读取
			{
				sb.append(line + "\n");
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		} finally
		{
			try
			{
				inputStream.close();
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		if (sb.length() != 0)
		{
			sb.deleteCharAt(sb.length() - 1); // 最后一个回车符是多余的，应该删除
		}
		return sb.toString();
	}

	public static List<String> readTxtFile(String filePath)
	{
		List<String> strList = new LinkedList<String>();
		try
		{
			String encoding = "UTF-8";
			File file = new File(filePath);
			if (file.isFile() && file.exists())
			{ // 判断文件是否存在
				InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);// 考虑到编码格式
				BufferedReader bufferedReader = new BufferedReader(read);
				String lineTxt = null;
				// 按行读取
				while ((lineTxt = bufferedReader.readLine()) != null)
				{
					strList.add(lineTxt);
				}
				read.close();
			} else
			{
				System.out.println("找不到指定的文件");
			}
		} catch (Exception e)
		{
			System.out.println("读取文件内容出错");
			e.printStackTrace();
		}
		return strList;
	}

}
